<template>
  <a-modal
    class="addProduct"
    :visible="visible"
    :title="operate === 'add' ? '添加商品' : '编辑商品'"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :closable="true"
    :confirmLoading="confirmLoading"
    width="900px"
    @cancel="closeModal()"
    @ok="handleSubmit"
  >
    <a-form-model
      class="group-bargaining-form"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
    >
      <a-form-model-item label="商品名称" prop="prizeName">
        <a-input
          allow-clear
          style="width: 300px"
          v-model="formData.prizeName"
          :disabled="false"
          placeholder="输入商品名称，限1-8字"
        />
      </a-form-model-item>
      <a-form-model-item label="商品类型" prop="prizeType">
        <a-radio-group v-model="formData.prizeType" @change="prizeTypeChange">
          <a-radio class="r-item" value="1"
            >优惠券
            <!-- <a-select v-model="formData.coupon" style="width: 120px">
              <a-select-option value="1">优惠券1</a-select-option>
              <a-select-option value="2">优惠券2</a-select-option>
            </a-select> -->
            <a-button
              key="submit"
              type="primary"
              @click="chooseCoupon"
              v-show="
                formData.prizeType === '1' && !formData.couponInfo.couponName
              "
            >
              选择优惠券
            </a-button>
            <span
              class="coupon"
              v-show="
                formData.prizeType === '1' && formData.couponInfo.couponName
              "
              @click="chooseCoupon"
              >{{ formData.couponInfo.couponName }}</span
            >
            <span
              class="couponStocks"
              v-show="
                formData.prizeType === '1' && formData.couponInfo.couponName
              "
              >优惠券库存：{{
                formData.couponInfo.couponStocks == -1
                  ? "不限量"
                  : formData.couponInfo.couponStocks
              }}</span
            >
          </a-radio>
          <a-radio class="r-item" value="2"
            >积分
            <a-input-number
              v-model="formData.integralCount"
              :disabled="formData.prizeType != 2"
              :min="1"
              :max="6000"
            />
          </a-radio>
          <a-radio class="r-item" value="3">赠品</a-radio>
        </a-radio-group>
        <div v-show="formData.prizeType === '3'">
          <div>
            领取有效时间：<a-input-number
              v-model="formData.validDay"
              :min="1"
              :max="100"
            />
            天
          </div>
          <div>
            <a-button
              key="submit"
              type="primary"
              @click="selectGiveaway"
              v-if="!formData.giftInfomation.goodsId"
            >
              选择赠品
            </a-button>
            <div class="giftBox" v-else>
              <div
                class="giftImg"
                :style="{
                  background: `url(${formData.giftInfomation.goodsPicture}) no-repeat 50% 50% /cover`,
                }"
                @click="selectGiveaway"
              >
                <div class="update">更换商品</div>
              </div>
              <div>
                <div
                  class="goodsStock"
                  v-if="formData.giftInfomation.remainingStock"
                >
                  赠品库存：{{ formData.giftInfomation.remainingStock }}
                </div>
                <div class="goodsname">
                  赠品名称：{{ formData.giftInfomation.goodsName }}
                  <span class="goodsNorm"
                    >赠品型号：{{ formData.giftInfomation.norm }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="数量" prop="amount">
        <div>
          <a-input-number v-model="formData.amount" :min="1" :max="maxAmount" />
          份
          <span class="tips">tips：商品总数量不能大于库存，若大于库存则取库存数</span>
        </div>
      </a-form-model-item>
      <a-form-model-item label="中奖概率" prop="odds">
        <a-input-number
          v-model="formData.odds"
          :min="0.0"
          :max="maxOdds"
          :step="0.01"
          :precision="2"
        />
        %
        <div style="line-height: 20px; margin-top: 5px">
          中奖概率为用户每次抽奖时独立事件的概率。举例：若中奖率为10%，<br />则每个用户中奖的概率为10%，并不是10个人中一定出现1个奖品<br />全部商品中奖概率之和不能大于100%
        </div>
      </a-form-model-item>
    </a-form-model>
    <template slot="footer">
      <a-button key="back" @click="closeModal"> 取消 </a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">
        确定
      </a-button>
    </template>
    <template>
      <gift-choose
        :pageVisible="pageVisible"
        @cancel="closegiftModal"
        @confirm="confirmData"
        :pageModelId="pageModelId"
        :goodsInfo="giftInfo"
        :tableData="tableData"
      ></gift-choose>
      <freebie
        :pageVisible="freebieVisible"
        @cancel="closefreebieModal"
        @confirm="confirmfreebieData"
        :pageModelId="freebieModelId"
        :goodsInfo="selectGoods"
      ></freebie>
      <specifiChoose
        :pageVisible="specifiVisible"
        @cancel="closeSpecifiModal"
        @confirm="confirmSpecifiData"
        :pageModelId="specifiModelId"
        :goodsInfo="selectGoods"
        :tableData="tableData"
      ></specifiChoose>
    </template>
  </a-modal>
</template>

<script>
import giftChoose from "./giftChoose.vue";
import freebie from "./freebie.vue";
import specifiChoose from "./specifiChoose.vue";
export default {
  name: "addProduct",
  components: {
    giftChoose,
    freebie,
    specifiChoose,
  },
  props: {
    operate: {
      type: String,
      default: "add",
    },
    editData: {
      type: Object,
      default: {},
    },
    goodsIndex: {
      type: String,
      default: "",
    },
    tableData: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      visible: false,
      title: "添加商品",
      confirmLoading: false,
      formData: {
        prizeName: "",
        prizeType: "1",
        // coupon: "1",
        integralCount: 1,
        amount: 1,
        odds: 1,
        validDay: 1,
        couponInfo: {
          couponName: "",
        },
        giftInfomation: {
          goodsPicture: "",
          goodsName: "",
          goodsId: "",
          norm: "",
          remainingStock: "",
        },
      },
      rules: {
        prizeName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 1, max: 8, message: "商品名称长度在1-8位", trigger: "blur" },
        ],
      },
      pageVisible: false,
      freebieVisible: false,
      giftInfo: {},
      pageModelId: "",
      freebieModelId: "",
      freebieInfo: {},
      specifiVisible: false,
      specifiModelId: "",
      selectGoods: {},
      maxOdds: 100,
      opratation: "comfirm", //区分是从选择商品取消还是从选择规格确定回到此页面
    };
  },
  computed: {
    maxAmount() {
      if (this.formData.prizeType == 1) {
        if (!this.giftInfo.remainingStock) {
          return Infinity;
        } else {
          if (this.giftInfo.remainingStock == -1) {
            return Infinity;
          } else {
            return this.giftInfo.remainingStock;
          }
        }
      } else if (this.formData.prizeType == 3) {
        if (!this.selectGoods.remainingStock) {
          return Infinity;
        } else {
          return this.selectGoods.remainingStock;
        }
      }
    },
  },
  methods: {
    // 确定提交
    handleSubmit() {
      this.confirmLoading = true;
      if (this.formData.prizeType == 1) {
        this.formData.giftInfomation = {
          goodsPicture: "",
          goodsName: "",
          goodsId: "",
          norm: "",
          remainingStock: "",
        };
        this.pageModelId = "";
        this.freebieModelId = "";
        this.specifiModelId = "";
      } else if (this.formData.prizeType == 2) {
        this.formData.couponInfo = {
          couponName: "",
        };
        this.formData.giftInfomation = {
          goodsPicture: "",
          goodsName: "",
          goodsId: "",
          norm: "",
          remainingStock: "",
        };
        this.pageModelId = "";
        this.freebieModelId = "";
        this.specifiModelId = "";
      } else if (this.formData.prizeType == 3) {
        this.formData.couponInfo = {
          couponName: "",
        };
        this.pageModelId = "";
      }
      let relationId;
      let params;
      if (this.formData.prizeType == 3) {
        // console.log(this.formData, "000000");
        // console.log(this.selectGoods, "555555");
        // console.log(this.editData);
        //区分是从选择商品取消还是从选择规格确定回到此页面
        console.log(this.opratation, "666666666666");
        if (this.opratation == "cancel") {
          params = {
            ...this.editData,
          };
        } else {
          relationId = this.selectGoods.id;
          params = {
            ...this.formData,
            ...this.selectGoods,
            relationId: relationId,
          };
        }
      } else {
        relationId = this.giftInfo.id;
        params = {
          ...this.formData,
          ...this.giftInfo,
          relationId: relationId,
        };
      }
      console.log(params, "33333");
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (params.prizeType == 1) {
            if (!this.formData.couponInfo.goodsId) {
              this.$message.error("请选择优惠券");
              return;
            }
            // delete params.relationId
            delete params.couponInfo;
            delete params.integralCount;
            delete params.validDay;
            this.visible = false;
            if (this.operate == "add") {
              this.$emit("comfirmGiftInfo", params);
            } else {
              this.$emit(
                "comfirmGiftInfo",
                params,
                this.operate,
                this.goodsIndex
              );
            }
          } else if (params.prizeType == 2) {
            if (!params.integralCount) {
              this.$message.error("积分数不能为空");
              return;
            }
            delete params.relationId;
            delete params.couponInfo;
            // delete params.integralCount
            delete params.validDay;
            this.visible = false;
            if (this.operate == "add") {
              this.$emit("comfirmGiftInfo", params);
            } else {
              this.$emit(
                "comfirmGiftInfo",
                params,
                this.operate,
                this.goodsIndex
              );
            }
          } else if (params.prizeType == 3) {
            if (!this.formData.giftInfomation.goodsId) {
              this.$message.error("请选择赠品");
              return;
            }
            this.visible = false;
            if (this.operate == "add") {
              this.$emit("comfirmGiftInfo", params);
            } else {
              this.$emit(
                "comfirmGiftInfo",
                params,
                this.operate,
                this.goodsIndex
              );
            }
          }
        } else {
          // this.$message.error("商品名称不能为空");
          return false;
        }
      });
    },
    // 取消
    closeModal() {
      this.visible = false;
      this.$emit("cancel", false);
    },
    closegiftModal() {
      this.pageVisible = false;
    },
    closefreebieModal(e) {
      this.freebieVisible = false;
      if (e == "cancel") this.opratation = "cancel";
    },
    closefreebieModalFromSpe() {
      this.freebieVisible = false;
      this.opratation = "comfirm";
    },
    closeSpecifiModal() {
      this.specifiVisible = false;
    },
    confirmData(e) {
      console.log(e);
      this.giftInfo = e;
      this.giftInfo.remainingStock = e.couponStocks * 1;
      this.pageModelId = e.id;
      this.formData.couponInfo.couponName = e.couponName;
      this.formData.couponInfo.goodsId = e.id;
      this.formData.couponInfo.couponStocks =
        e.couponStocks == -1 ? "不限量" : e.couponStocks;
      this.pageVisible = false;
    },
    confirmfreebieData(e) {
      console.log(e);
      this.specifiVisible = true;
      this.selectGoods = e;
    },
    confirmSpecifiData(e) {
      this.closefreebieModalFromSpe();
      this.closeSpecifiModal();
      console.log(e);
      this.selectGoods = e;
      this.selectGoods.id = e.goodsSpecId;
      this.freebieModelId = e.goodsId;
      this.specifiModelId = e.goodsSpecId;
      this.formData.giftInfomation.goodsPicture = e.goodsPicture;
      this.formData.giftInfomation.goodsName = e.goodsName;
      this.formData.giftInfomation.goodsType = e.goodsType;
      this.formData.giftInfomation.goodsId = e.goodsId;
      this.formData.giftInfomation.remainingStock = e.remainingStock * 1;
      this.formData.giftInfomation.norm = e.norm;
      // this.pageVisible = false;
    },
    // 选择赠品
    selectGiveaway() {
      // this.$message.info("选择赠品");
      this.freebieVisible = true;
    },
    //选择优惠券
    chooseCoupon() {
      this.pageVisible = true;
      if (this.formData.couponInfo.couponName && this.operate != "add") {
        this.pageModelId = this.giftInfo.id;
      } else {
        this.pageModelId = "";
      }
    },
    prizeTypeChange(e) {
      // if (e.target.value == 1) {
      //   // this.formData.couponInfo = {
      //   //   couponName: "",
      //   // };
      // } else if (e.target.value == 2) {
      //   this.formData.couponInfo = {
      //     couponName: "",
      //   };
      //   this.pageModelId = "";
      // } else if (e.target.value == 3) {
      //   this.formData.couponInfo = {
      //     couponName: "",
      //   };
      //   this.pageModelId = "";
      // }
    },
    async getcoupon(params) {
      let res = await this.$get("/coupon/query", {
        id: params,
      });
      if (res && res.returnCode == 1000) {
        if (res.dataInfo != null) {
          console.log(res.dataInfo, "111");
          this.formData.couponInfo.couponName = res.dataInfo.couponName;
          this.formData.couponInfo.couponStocks = res.dataInfo.couponStocks;
          this.formData.couponInfo.goodsId = res.dataInfo.id;
          this.giftInfo = res.dataInfo;
          console.log(this.giftInfo, "0000");
        }
      }
    },
    // async getGoodInfo(goodsId) {
    //   let res = await this.$get(
    //     "goldenhome/gh/lottery/admin_/giving/goodsmanage/id",
    //     {
    //       goodsId: goodsId,
    //     }
    //   );
    //   if (res && res.returnCode == 1000) {
    //     // this.formData.giftInfomation.norm =
    //   }
    // },
  },
  watch: {
    visible(n) {
      if (n) {
        if (this.operate == "add") {
          this.formData = {
            prizeName: "",
            prizeType: "1",
            // coupon: "1",
            integralCount: 1,
            amount: 1,
            odds: 1,
            validDay: 1,
            couponInfo: {
              couponName: "",
            },
            giftInfomation: {
              goodsPicture: "",
              goodsName: "",
              goodsId: "",
              norm: "",
              remainingStock: "",
            },
          };
          this.giftInfo = {};
          this.relationId = "";
          this.freebieModelId = "";
          this.specifiModelId = "";
          this.maxOdds = 100;
          let num = 0;
          this.tableData.forEach((item) => {
            num = num + item.odds;
          });
          this.maxOdds = this.maxOdds - num;
        } else {
          this.maxOdds = 100;
          let num = 0;
          this.tableData.forEach((item) => {
            num = num + item.odds;
          });
          this.maxOdds = this.maxOdds - num + this.editData.odds;
          this.formData = {
            prizeName: this.editData.prizeName,
            prizeType: this.editData.prizeType + "",
            // coupon: "1",
            integralCount: this.editData.integralCount || 1,
            amount: this.editData.amount || 1,
            odds: this.editData.odds || 1,
            validDay: this.editData.validDay || 1,
            chooseAmount: this.editData.chooseAmount || 0,
            issueCount: this.editData.issueCount || 1,
            couponInfo: {
              couponName: "",
            },
            giftInfomation: {
              goodsPicture: "",
              goodsName: "",
              goodsId: "",
              norm: "",
              remainingStock: "",
            },
          };
          if (this.formData.prizeType == 1) {
            this.giftInfo = {};
            // this.formData.couponInfo.goodsId =
            this.getcoupon(this.editData.relationId);
          } else if (this.formData.prizeType == 3) {
            this.selectGoods = {};
            this.formData.giftInfomation.goodsPicture =
              this.editData.goodsPicture;
            this.formData.giftInfomation.goodsName = this.editData.goodsName;
            this.formData.giftInfomation.goodsType = this.editData.goodsType;
            this.formData.giftInfomation.goodsId = this.editData.goodsId;
            this.formData.giftInfomation.remainingStock =
              this.editData.remainingStock;
            this.formData.giftInfomation.norm =
              this.editData.norm || this.editData.goodsNorm;
            this.freebieModelId = this.editData.goodsId;
            this.specifiModelId = this.editData.relationId;
            this.selectGoods = {
              ...this.formData.giftInfomation,
              id: this.editData.relationId,
            };
            // this.getGoodInfo(this.editData.goodsId);
          }
          this.relationId =
            this.editData.prizeType == 2 ? "" : this.editData.relationId;
        }
      } else {
        this.opratation == "comfirm";
      }
    },
  },
};
</script>

<style scoped lang="less">
.addProduct {
  .r-item {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}
.coupon {
  color: #1890ff;
  font-size: 18px;
  margin-left: 10px;
  text-decoration: underline;
}
.couponStocks {
  margin-left: 10px;
}
.giftBox {
  margin-top: 15px;
  display: flex;
  align-items: center;
  .giftImg {
    width: 50px;
    height: 50px;
    margin-right: 20px;
    position: relative;
    cursor: pointer;
    .update {
      width: 100%;
      height: 20px;
      text-align: center;
      font-size: 8px;
      color: #fff;
      background: rgba(0, 0, 0, 0.5);
      position: absolute;
      bottom: 0;
      line-height: 20px;
    }
  }
  .goodsNorm {
    margin-left: 20px;
  }
}
.tips {
  margin-left: 15px;
  color: #b8b8b8;
}
</style>

